package com.qiall.gateway.controller;

import com.qiall.assertutil.Assert;
import com.qiall.common.entity.PageQuery;
import com.qiall.common.entity.PageResponse;
import com.qiall.common.exception.BusinessResult;
import com.qiall.gateway.controller.convert.AddApiPreCheckActivity;
import com.qiall.gateway.controller.convert.ApiInfoTrans;
import com.qiall.gateway.controller.request.ApiDTO;
import com.qiall.gateway.controller.request.AddApiRequest;
import com.qiall.gateway.controller.request.QueryApiInfoRequest;
import com.qiall.gateway.data.entity.ApiInfo;
import com.qiall.gateway.data.mapper.ApiInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 吴金辉
 */
@RestController
@RequestMapping("/apiManage")
public class ApiManageController {
    @Autowired
    ApiInfoTrans apiInfoTrans;
    @Autowired
    private ApiInfoMapper apiInfoMapper;

    @Autowired
    private AddApiPreCheckActivity addApiPreCheckActivity;

    @PostMapping("/addOrUpdateApi")
    public BusinessResult<Void> addApi(@RequestBody AddApiRequest addApiRequest) {
        addApiPreCheckActivity.handler(addApiRequest, null);
        ApiInfo apiInfo = apiInfoTrans.trans(addApiRequest);
        if (addApiRequest.getId() != null && !addApiRequest.getId().equals(0)) {
            apiInfoMapper.update(apiInfo);
            return BusinessResult.success(null);
        }
        // 插入前判断是否有重复
        ApiInfo findByPath = apiInfoMapper.selectByApiPath(addApiRequest.getApiPath());
        Assert.isNull(findByPath,"接口已经存在");
        apiInfoMapper.insert(apiInfo);
        return BusinessResult.success(null);
    }

    @PostMapping("/getApiInfoPage")
    public BusinessResult<PageResponse<ApiDTO>> getApiInfoPage(@RequestBody QueryApiInfoRequest request) {
        ApiInfo apiInfo = apiInfoTrans.trans(request);
        PageQuery pageQuery = request.getPageQuery();
        int count = apiInfoMapper.count(apiInfo);
        if (count == 0) {
            BusinessResult.success(PageResponse.nullValue(pageQuery));
        }
        List<ApiInfo> apiInfos = apiInfoMapper.selectByPage(apiInfo, pageQuery.offset(), pageQuery.limit());
        List<ApiDTO> apiDTOS = apiInfos.stream().map(x -> apiInfoTrans.trans(x)).collect(Collectors.toList());
        return BusinessResult.success(PageResponse.withValue(pageQuery, count, apiDTOS));
    }

}
